﻿using System;
using System.Data;
using System.Data.SqlClient;
using Reactor.Environment;

namespace Reactor.Workflow.Extensions
{
    public class PersistedPropertiesExtension
    {
        private readonly PlatformConnectionData _platformConnectionData;

        /// <summary>
        /// Initializes a new instance of the <see cref="PersistedPropertiesExtension"/> class.
        /// </summary>
        /// <param name="platformConnectionData">The platform connection data.</param>
        public PersistedPropertiesExtension(PlatformConnectionData platformConnectionData)
        {
            if (platformConnectionData == null) throw new ArgumentNullException("platformConnectionData");

            _platformConnectionData = platformConnectionData;
        }

        public void PromoteProperty(Guid workflowId, string propertyName, object value)
        {
            using (var sqlConnection = new SqlConnection(_platformConnectionData.DatabaseConnectionString))
            {
                using (var cmd = new SqlCommand("dbo.[InsertPersistedProperty]"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@workflowId", workflowId);
                    cmd.Parameters.AddWithValue("@propertyName", propertyName);
                    cmd.Parameters.AddWithValue("@propertyValue", value);

                    sqlConnection.Open();
                    cmd.Connection = sqlConnection;
                    cmd.ExecuteNonQuery();
                }
            }
        }

        public T GetPersistedPropertyValue<T>(Guid workflowId, string propertyName)
        {
            object value;
            using (var sqlConnection = new SqlConnection(_platformConnectionData.DatabaseConnectionString))
            {
                using (var cmd = new SqlCommand("dbo.[GetPersistedPropertyByWorkflowAndName]"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@workflowId", workflowId);
                    cmd.Parameters.AddWithValue("@propertyName", propertyName);

                    sqlConnection.Open();
                    cmd.Connection = sqlConnection;

                    value = cmd.ExecuteScalar();
                }
            }

            return (value == null) ? default(T) : (T)value;
        }
    }
}
